<template>
  <div>
    <a-card
      :tab-list="tabList"
      :active-tab-key="currentTab"
      @tabChange="changeTab"
    >
      <a-form-model
        ref="form"
        :model="searchForm"
        :rules="rules"
        :label-col="{ span: 8 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-row gutter="24">
          <a-col
            :span="3"
            :md="3"
            :xl="3"
            style="
              padding-left: 0px;
              padding-right: 0px;
              width: 280px;
              margin-right: 0px;
              margin-left: 10px;
            "
          >
            <a-form-model-item label="开单日期">
              <a-range-picker
                v-model="searchForm.dateRange"
                @change="changeDate"
                style="width: 200px"
                :ranges="ranges"
              />
            </a-form-model-item>
          </a-col>
          <a-col
            :span="4"
            :md="8"
            :xl="6"
            style="
              padding-left: 0px;
              padding-right: 0px;
              width: 200px;
              margin-right: 0px;
              margin-left: 0px;
            "
          >
            <a-form-model-item prop="client" label="客户">
              <a-select
                showSearch
                v-model="searchForm.client"
                style="width: 100%"
                :filterOption="filterOption"
                allowClear
              >
                <a-select-option
                  v-for="item in clientsItems"
                  :key="item.id"
                  :value="item.id"
                >
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col
            :span="4"
            :md="8"
            :xl="6"
            style="
              padding-left: 0px;
              padding-right: 0px;
              width: 200px;
              margin-right: 0px;
              margin-left: 0px;
            "
          >
            <a-form-model-item prop="goods" label="存货">
              <a-select
                showSearch
                v-model="searchForm.goods"
                style="width: 100%"
                :filterOption="filterOption"
                allowClear
              >
                <a-select-option
                  v-for="item in goodsItems"
                  :key="item.id"
                  :value="item.id"
                >
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col
            :span="3"
            :md="3"
            :xl="3"
            style="
              padding-left: 0px;
              padding-right: 0px;
              width: 180px;
              margin-right: 20px;
              margin-left: 10px;
            "
          >
            <a-form-model-item prop="search" label="搜索">
              <a-input
                v-model="searchForm.search"
                allowClear
                placeholder="销售单号/规格尺寸"
                style="
                  padding-left: 0px;
                  padding-right: 0px;
                  width: 180px;
                  margin-right: 10px;
                "
              />
              <!-- <a-input v-model="searchForm.search" allowClear :placeholder="NewdateToString" /> -->
            </a-form-model-item>
          </a-col>
          <a-col
            :span="3"
            :md="3"
            :xl="3"
            style="width: 280px; margin-left: 40px"
          >
            <a-form-model-item>
              <a-button-group>
                <a-button type="primary" :loading="loading" @click="search"
                  ><a-icon type="search" />查询</a-button
                >
                <a-button :loading="downloadLoading" @click="handleDownload"
                  ><a-icon type="file-excel" />导出</a-button
                >
              </a-button-group>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>

      <a-descriptions
        :column="{ xxl: 7, xl: 7, lg: 7, md: 2, sm: 2, xs: 1 }"
        style="text-align: center"
      >
        <a-descriptions-item label="销售次数"
          ><span class="total">{{ totalCount }}</span></a-descriptions-item
        >
        <a-descriptions-item label="销售件数(件)"
          ><span class="total">{{ totalquantity }}</span></a-descriptions-item
        >
        <a-descriptions-item label="材料总重量(市斤)"
          ><span class="total">{{
            total_total_weight
          }}</span></a-descriptions-item
        >
        <a-descriptions-item label="材料金额(元)"
          ><span class="total">{{ total_clAmount }}</span></a-descriptions-item
        >
        <a-descriptions-item label="总条数(条)"
          ><span class="total">{{
            total_total_strip_count
          }}</span></a-descriptions-item
        >
        <a-descriptions-item label="烫工金额(元)"
          ><span class="total">{{ total_jgAmount }}</span></a-descriptions-item
        >
        <a-descriptions-item label="总金额(元)"
          ><span class="total">{{
            total_totalAmount
          }}</span></a-descriptions-item
        >
      </a-descriptions>

      <div>
        <flow-pane
          v-show="currentTab === 'flow'"
          :items="items"
          :loading="loading"
          :pagination="pagination"
          @tableChange="tableChange"
          key="flow-pane"
        />
        <!-- <goods-pane
          v-show="currentTab === 'goods'"
          :items="items"
          :loading="loading"
          :pagination="pagination"
          @tableChange="tableChange"
          key="goods-pane"
        /> -->
      </div>
      <div style="text-align: center; margin-top: 12px">
        <a-spin :spinning="loading && searchForm.page > 1" />
      </div>
    </a-card>
  </div>
</template>

<script>
import {
  salesReportStatistics,
  salesReportDetialsList,
  salesReportByGoodsList,
} from "@/api/report";
import { List } from "@/api/common";
import { datetimeToString, filterOption } from "@/utils/common";
import {
  goodsClassificationOption,
  clientsOption,
  goodsOption,
} from "@/api/option";
import NP from "number-precision";
import moment from "moment";

export default {
  name: "SalesReport",
  components: {
    FlowPane: () => import("./flowPane"),
    // GoodsPane: () => import("./goodsPane"),
  },
  data() {
    return {
      downloadLoading: false,
      downloadList: [],
      ranges: {
        今日: [moment().startOf("day"), moment().startOf("day")],
        昨日: [moment().subtract(1, "days"), moment().subtract(1, "days")],
        本周: [
          moment().week(moment().week()).startOf("week"),
          moment().week(moment().week()).endOf("week"),
        ],
        上周: [
          moment().subtract(1, "week").startOf("week"),
          moment().subtract(1, "week").endOf("week"),
        ],
        本月: [moment().startOf("month"), moment().startOf("day")],
        上月: [
          moment().subtract(1, "month").startOf("month"),
          moment().subtract(1, "month").endOf("month"),
        ],
      },
      NP,
      currentTab: "flow",
      radioValue: "0",
      tabList: [
        {
          key: "flow",
          tab: "销售明细",
        },
        // {
        //   key: 'goods',
        //   tab: '按产品汇总',
        // },
      ],
      searchForm: {
        dateRange: [moment().startOf("day"), moment().startOf("day")],
        // dateRange: [],
        category: null,
        page: 1,
        client: null,
        page_size: 15,
        ordering: "-create_time",
        search: null,
      },
      loading: true,
      categoryItems: [],
      clientsItems: [],
      goodsItems: [],
      total: {
        total_count: 0,
        total_clAmount: 0,
        total_jgAmount: 0,
        total_totalAmount: 0,
      },
      items: [],
      pagination: { current: 1, total: 0, pageSize: 15 },
    };
  },
  computed: {
    totalCount() {
      return this.total.total_quantity ? this.total.total_count : 0;
    },
    totalquantity() {
      return this.total.total_quantity ? this.total.total_quantity : 0;
    },
    total_clAmount() {
      return this.total.total_clAmount
        ? NP.round(this.total.total_clAmount, 2)
        : 0;
    },
    total_total_weight() {
      return this.total.total_total_weight
        ? NP.round(this.total.total_total_weight, 2)
        : 0;
    },
    total_total_strip_count() {
      return this.total.total_total_strip_count
        ? NP.round(this.total.total_total_strip_count, 0)
        : 0;
    },
    total_jgAmount() {
      return this.total.total_jgAmount
        ? NP.round(this.total.total_jgAmount, 2)
        : 0;
    },
    total_totalAmount() {
      return this.total.total_totalAmount
        ? NP.round(this.total.total_totalAmount, 2)
        : 0;
    },
  },
  methods: {
    // 将输入的内容与显示的内容进行匹配
    filterOption(value, option) {
      return filterOption(value, option);
    },
    getNewdownloadList(downloadList) {
      let o = {
        index: "合计",
        quantity: 0,
        total_weight: 0,
        material_amount: 0,
        total_strip_count: 0,
        ironing_amount: 0,
        total_amount: 0,
      };

      if (downloadList) {
        let i = 0;
        downloadList.forEach((e) => {
          i += 1;
          e["index"] = i;
          o.quantity += parseFloat(e.quantity);
          o.total_weight += parseFloat(e.total_weight);
          o.material_amount += parseFloat(e.material_amount);
          o.total_strip_count += parseFloat(e.total_strip_count);
          o.ironing_amount += parseFloat(e.ironing_amount);
          o.total_amount += parseFloat(e.total_amount);
        });
        downloadList.push(o);
      } else {
        downloadList = [];
      }
    },
    handleDownload() {
      this.loading = true;
      this.downloadLoading = true;
      let form = {
        start_date:
          this.searchForm.dateRange.length > 0
            ? this.searchForm.dateRange[0].format("YYYY-MM-DD")
            : null,
        end_date:
          this.searchForm.dateRange.length > 0
            ? this.searchForm.dateRange[1].format("YYYY-MM-DD")
            : null,
        client: this.searchForm.client,
        goods: this.searchForm.goods,
        page: this.searchForm.page,
        page_size: 99999,
        search: this.searchForm.search,
      };
      if (form.end_date) {
        form.end_date = moment(form.end_date)
          .add(1, "days")
          .format("YYYY-MM-DD");
      }
      List(form, "sales_reports/detials").then((response) => {
        const resp = response.data;
        this.downloadList = response.results;
        this.getNewdownloadList(this.downloadList);
        // this.downloadList.forEach(e => {
        //     e.jgry_items=this.jgry_items2names(e.jgry_items)
        //     e.is_void=e.is_void?'已作废':"正常"
        // });
        // console.log('this.downloadList:',this.downloadList )
        this.searchForm.page_size = 15;
        import("@/vendor/Export2ExcelNew").then((excel) => {
          const tHeader1 = [
            "序号",
            "开单时间",  
            "客户",
            "销售单号",
            "品名",
            "型号尺寸",
            "件数",
            "单重",
            "重量",
            "材料单价",
            "材料金额(元)",
            "单条数",
            "总条数",
            "烫工单价",
            "烫工金额(元)",
            "总金额",
            "经手人",
 
          ];
          const filterVal = [
            "index",
            "create_time",
            "client_name",
            "sales_order_number",
            "goods_name",
            "specification",
            "quantity",
            "unit_weight",
            "total_weight",
            "material_unit_price",
            "material_amount",
            "unit_strip_count",
            "total_strip_count",
            "ironing_unit_price",
            "ironing_amount",
            "total_amount",
            "handler_name",
          ];
          //const filterVal = tHeader;
          //不要将下载数据与显示数据列表用同一个变量，否则要出问题
          const list = this.downloadList;
          let downloadList = list;

          const data = this.formatJson(filterVal, downloadList);
          const title = ["销售明细" + datetimeToString(new Date())];
          const sheetname = "销售明细";
          const merges = ["A1:P1"];
          excel.export_json_to_excel({
            title,
            header: tHeader1,
            // multiHeader:[tHeader1],
            data,
            filename: "销售明细" + datetimeToString(new Date()),
            merges,
            // autoWidth: this.autoWidth,
            autoWidth: this.autoWidth,
            bookType: this.bookType,
            sheetname,
          });
          this.loading = false;
          this.downloadLoading = false;
        });
      });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) =>
        filterVal.map((j) => {
          if (j === "timestamp") {
            return parseTime(v[j]);
          } else {
            return v[j];
          }
        })
      );
    },
    initailize() {
      if (this.$route.query.type) {
        this.currentTab = this.$route.query.type;
      } else {
        this.$router.replace({ query: { type: this.currentTab } });
      }

      this.list();
      goodsClassificationOption({ page_size: 99999 }).then((resp) => {
        this.categoryItems = resp.results;
      });
      clientsOption({ page_size: 999999, is_active: true }).then((data) => {
        this.clientsItems = data.results;
      });
      goodsOption({ page_size: 999999, is_active: true }).then((data) => {
        this.goodsItems = data.results;
      });
    },
    list() {
      let form = {
        start_date:
          this.searchForm.dateRange.length > 0
            ? this.searchForm.dateRange[0].format("YYYY-MM-DD")
            : null,
        end_date:
          this.searchForm.dateRange.length > 0
            ? this.searchForm.dateRange[1].format("YYYY-MM-DD")
            : null,
        category: this.searchForm.category,
        page: this.searchForm.page,
        page_size: this.searchForm.page_size - 1,
        search: this.searchForm.search,
        client: this.searchForm.client,
        goods: this.searchForm.goods,
        ordering: this.searchForm.ordering,
      };
      if (form.end_date) {
        form.end_date = moment(form.end_date)
          .add(1, "days")
          .format("YYYY-MM-DD");
      }

      this.loading = true;
      salesReportStatistics(form).then((resp) => {
        this.total = resp;
      });
      if (this.currentTab === "flow") {
        salesReportDetialsList(form)
          .then((resp) => {
            this.items = resp.results;
            this.addSummaryToItems();
            this.pagination.total = resp.count;
          })
          .finally(() => {
            this.loading = false;
          });
      } else {
        salesReportByGoodsList(form)
          .then((resp) => {
            // this.items = resp.results;
            console.log("this.items:", this.items);

            console.log("this.addSummaryToItems()");
            this.pagination.total = resp.count;
          })
          .finally(() => {
            this.loading = false;
          });
      }
    },
    addSummaryToItems() {
      let totalquantity = 0;
      let totalWeight = 0;
      let totalstrip_count = 0;
      let totalMaterialAmount = 0;
      let totalIroningAmount = 0;
      let totalAmount = 0;
      console.log("totalWeight", totalWeight);
      // 计算各项合计
      for (let record of this.items) {
        totalquantity += parseFloat(record.quantity) || 0;
        totalWeight += parseFloat(record.total_weight) || 0;
        totalstrip_count += record.total_strip_count || 0;
        totalMaterialAmount += parseFloat(record.material_amount) || 0;
        totalIroningAmount += parseFloat(record.ironing_amount) || 0;
        totalAmount += parseFloat(record.total_amount) || 0;
      }
      // 创建合计对象
      const summaryItem = {
        index: "",
        create_time: "",
        client_name: "合计",
        sales_order_number: "",
        goods_name: "",
        quantity: totalquantity,
        total_weight: totalWeight.toFixed(2),
        total_strip_count: totalstrip_count,
        material_amount: totalMaterialAmount.toFixed(2),
        ironing_amount: totalIroningAmount.toFixed(2),
        total_amount: totalAmount.toFixed(2),
        handler_name: "",
      };
      // 将合计对象添加到 items 数组末尾
      this.items.push(summaryItem);
    },
    tableChange(pagination, filters, sorter) {
      this.searchForm.page = pagination.current;
      this.pagination.current = pagination.current;
      this.searchForm.ordering = `${sorter.order == "descend" ? "-" : ""}${
        sorter.field
      }`;
      console.log("this.searchForm.ordering:", this.searchForm.ordering);
      this.list();
    },
    search() {
      this.searchForm.page = 1;
      this.pagination.current = 1;
      this.list();
    },
    changeTab(key) {
      this.currentTab = key;
      this.$router.replace({ query: { type: this.currentTab } });
      this.resetForm();
      this.search();
    },
    changeRadio(evt) {
      let value = evt.target.value;
      if (value < 0) {
        this.searchForm.dateRange = [
          moment().startOf("day").add(value, "day"),
          moment().startOf("day"),
        ];
      } else {
        this.searchForm.dateRange = [
          moment().startOf("day").subtract(value, "day"),
          moment().startOf("day").subtract(value, "day"),
        ];
      }
      this.search();
    },
    changeDate() {
      this.radioValue = null;
      this.search();
    },
    changeCategory() {
      this.search();
    },
    resetForm() {
      this.radioValue = "0";
      this.searchForm = {
        dateRange: [moment().startOf("day"), moment().startOf("day")],
        category: null,
        page: 1,
        page_size: 16,
      };
    },
  },
  mounted() {
    this.initailize();
  },
};
</script>

<style scoped>
.total {
  color: #a94442;
}
</style>